<?php
class Security {

	const SESSION_INITIATED_PARAMETER = 'initiated';
	const SESSION_TIMESTAMP_PARAMETER = 'timestamp';


	final static function sessionStart($restart_time = true) {
		if (!isset($_SESSION)) {
			session_start();
			if (!isset($_SESSION[self::SESSION_INITIATED_PARAMETER])) {
				session_regenerate_id();
				$_SESSION[self::SESSION_INITIATED_PARAMETER] = true;
			}
			if (User::isLoggedIn()) {
				if (isset($_SESSION[self::SESSION_TIMESTAMP_PARAMETER])) {
					if (time() - $_SESSION[self::SESSION_TIMESTAMP_PARAMETER] > self::getSessionTime()) {
						session_unset();
					} elseif ($restart_time){
						$_SESSION[self::SESSION_TIMESTAMP_PARAMETER] = time();
					}
				}
			}
		}
	}

	final static function getUserIp() {
		return $_SERVER['REMOTE_ADDR'];
	}

	final static function correctHttpRefererRedirection() {
		if (!isset($_SERVER['HTTP_REFERER'])) {
			$_GET[Security::SESSION_PAGE_PARAMETER] = Constants::PAGE_ERROR_GET_PARAMETER;
			headers("Location: index.html");
		}
		$referer = $_SERVER['HTTP_REFERER'];
		$host = $_SERVER['HTTP_HOST'];
		if (!strpos($referer, $host)) {
			$_GET[Security::SESSION_PAGE_PARAMETER] = Constants::PAGE_ERROR_GET_PARAMETER;
			headers("Location: index.html");
		}
	}
}